<template>
  <Teleport to="body">
    <div class="container" :style="style">
      <textarea ref="nTextareaRef" v-model="val" wrap="off" class="n-textarea" :style="textareaStyle" @keyup.esc="cancel" @input="handleInput"></textarea>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue'
import stageModal, { stageModalTextareaSwitch } from '@renderer/utils/stageModal'
import { getPixiData } from '@renderer/store/modules/usePixiStore'
const nTextareaRef = ref<HTMLTextAreaElement | null>(null)
const props = defineProps({
  textUid: {
    required: true,
    type: Number,
  },
})
const modelValue = defineModel<Wx.Card.Data>({
  required: true,
})

const attrName = computed(() => {
  const pixiData = getPixiData(props.textUid)
  return pixiData.attrName as string
})
const val = ref<string>('')
const oldVal = ref<string>('')
const displayStyle = ref({
  display: 'none',
})
const locationStyle = ref<Record<string, string | number>>({
  top: '40%',
  left: '50%',
  width: '20rem',
  height: '20rem',
  maxHeight: '20rem',
})

const style = computed(() => {
  return { ...displayStyle.value, ...locationStyle.value }
})

const textareaStyle = ref({
  height: 'auto',
  width: '20rem',
  maxWidth: '20rem',
})

watch(stageModalTextareaSwitch, (val) => {
  displayStyle.value.display = val ? 'flex' : 'none'
})

const init = (
  text: string,
  param = {
    top: '40%',
    left: '50%',
    width: '20rem',
    height: '20rem',
  },
): void => {
  stageModal() // 初始化透明蒙版
  stageModalTextareaSwitch.value = true
  val.value = text
  oldVal.value = text
  displayStyle.value.display = 'block'
  locationStyle.value.left = param.left
  locationStyle.value.top = param.top
  locationStyle.value.width = param.width
  locationStyle.value.maxWidth = param.width
  locationStyle.value.height = param.height
  locationStyle.value.maxHeight = param.height

  textareaStyle.value.width = param.width
  textareaStyle.value.maxWidth = param.width
  nextTick(() => {
    nTextareaRef.value?.focus()
  })
}

const handleInput = (): void => {
  modelValue.value[attrName.value as Wx.Card.DiyText] = val.value
  textareaStyle.value.height = 'auto'
  textareaStyle.value.height = nTextareaRef.value!.scrollHeight + 'px'
}

const cancel = (): void => {
  val.value = oldVal.value
  modelValue.value[attrName.value as Wx.Card.DiyText] = val.value
  stageModalTextareaSwitch.value = false
}

defineExpose({
  init,
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  position: fixed;
  justify-content: center;
  align-items: center;
  border-radius: 0.5rem;
  background-color: #efd9af;
}
.n-textarea {
  font-size: 1.2rem;
  font-family: 'RZFont';
  border: none;
  text-align: center;
  overflow: hidden;
  word-break: break-all;
  resize: none;
  background-color: #efd9af;
  &:focus {
    outline: none;
    // caret-color: transparent;
  }
}
</style>
